package com.mischa.atc.gui;

import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Label;
import java.awt.Panel;
import java.util.Timer;
import java.util.TimerTask;

import javax.rmi.CORBA.Util;

import com.mischa.atc.Controller;
import com.mischa.atc.Flight;
import com.mischa.atc.RadarScreen;
import com.mischa.atc.RadarScreenDrawer;
import com.mischa.atc.Utilities;
import com.mischa.atc.clearances.AltitudeClearance;
import com.mischa.atc.clearances.HeadingClearance;

public class ATC_Applet extends Applet implements RadarScreenDrawer {
	
	private static final long serialVersionUID = 1L;
	
	private static final int SIZE = 50;
	
	private RadarScreen _radarScreen;
	private Controller _atcController;
	private RadarScreenCanvas _canvas;
	private Label _status;
	
	public ATC_Applet() {
		_atcController = new Controller();

		_radarScreen = new RadarScreen(_atcController, this);
		_radarScreen.setDisplayRangeInNM(SIZE);
				
		_canvas = new RadarScreenCanvas();
		_canvas.setRadius(SIZE);
		
		_status = new Label();
		
		final float sweepTime = 2f; // 2 seconds to go around
		final int sectorWidth = 5;	// sweep in steps of 5 degrees for smooth animation
		final float timeStep = sweepTime / (360 / sectorWidth);
		new Timer().scheduleAtFixedRate(new TimerTask() {
			
			@Override
			public void run() {
				_radarScreen.sweep(sectorWidth, sweepTime);
			}
		}, 0, (int)(1000 * timeStep));
	}
	
	@Override
	public void paint(Graphics g) {
		super.paint(g);
		_canvas.repaint();
	}
	
	@Override
	public void init() {
	
		setLayout(new BorderLayout());
		_canvas.setBounds(getBounds());
		add(_canvas, BorderLayout.CENTER);
		
		Panel _statusBar = new Panel();		
		_statusBar.add(_status);
		add(_statusBar, BorderLayout.SOUTH);
		
		// Create some flights at 1 minute into the simulation
		for(int i = 0; i <= 5; ++i)
		{
			Flight flight = _atcController.addFlight();
			flight.update(5 * 60);
			// Clear to random heading and altitude
			flight.clear(new HeadingClearance(Utilities.randomNumberBetween(1, 360)), true);
			flight.clear(new AltitudeClearance(1000 * Utilities.randomNumberBetween(2, 13)), false);
		}		
		
		this.resize(500, 500);
	}
	
	@Override
	public void DrawFlight(Flight flight, float x, float y) {		
		_canvas.DrawFlight(flight, x, y);
		_status.setText("Drew " + flight.toString());
	}
	
	@Override
	public void sweeping(int heading) {
		_canvas.sweeping(heading);
	}

	@Override
	public void flightOutOfRange(Flight flight) {
		_canvas.flightOutOfRange(flight);
	}

}
